package com.chenx.ps_server;


import android.os.Environment;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import fi.iki.elonen.NanoHTTPD;

public class SimpleServer extends NanoHTTPD {

    public SimpleServer() {
        super(1234);
    }

    @Override
    public Response serve(IHTTPSession session) {
//        LogTools.d(TAG, "OnRequest:" + session.getUri());
        String uri = session.getUri();//索引文件名
        String pathname="";
        if(!uri.equals("/"))
        {
            pathname = Environment.getExternalStorageDirectory().toString() +"/ps4/ps4"+uri;
        }else {
             pathname = Environment.getExternalStorageDirectory().toString() +"/ps4/ps4/index.html";
        }

//        LogTools.d(TAG, path + uri);
        return FileStream(session,pathname);
    }

    public Response FileStream(IHTTPSession session, String pathname) {
        try {
            FileInputStream fis = new FileInputStream(pathname);
//            LogTools.d(TAG, pathname);

            //Response response = new Response(Response.Status.OK, readHtml(pathname), fis, -1L);
           // return response;
            
           return NanoHTTPD.newChunkedResponse(Response.Status.OK,"text/html",fis);
//            return NanoHTTPD.Response.newChunkedResponse(Response.Status.OK,readHtml(pathname),fis);

        //  return  new Response();
            // Response(readHtml(pathname));
        } catch (FileNotFoundException e){
            e.printStackTrace();
           // return response404(session,pathname);
            return null;
        }
    }

    private String readHtml(String pathname) {
        BufferedReader br=null;
        StringBuffer sb = new  StringBuffer();
        try {
            br=new BufferedReader(new InputStreamReader(new FileInputStream(pathname),  "UTF-8"));
            String temp=null;
            while((temp=br.readLine())!=null){
                sb.append(temp);
            }
        } catch (FileNotFoundException e) {
//            LogTools.e(TAG, "Missing operating system!");
            e.printStackTrace();
        } catch (IOException e) {
//            LogTools.e(TAG, "write error!");
            e.printStackTrace();
        }
//        LogTools.d(TAG, sb.toString());
        return sb.toString();
    }
}
